<?php
namespace PsiFramework\Applications\DefaultApp\Classes\Actions\Util;

use PsiFramework\Classes\Util\Object\Image;
use PsiFramework\Classes\Util\Object\File;

import("Classes.Actions.AbstractAction");
import("Classes.Util.Object.Identification");

use \PsiFramework\Classes\Actions\AbstractAction;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Classes\Util\Object\Date;
use \PsiFramework\Applications\DefaultApp\Classes\Model\Trace;
use \PsiFramework\Classes\Util\Manager\ApplicationManager;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The Trace Action
 *
 * This action is used to crop images
 *
 * @package Actions.Util
 */
class CropAction extends AbstractAction
{

    /**
     * Function executed by the controller
     *
     * It crops the image
     *
     * @return Response    the response to the action execution
     */
    public function execute()
    {
        parent::execute();
        
        $realPath = $this->_request->getParameter('realPath');
        $x1 = $this->_request->getParameter('x1');
        $y1 = $this->_request->getParameter('y1');
        $croppedWidth = $this->_request->getParameter('width');
        $croppedHeight = $this->_request->getParameter('height');
        $targetWidth = $this->_request->getParameter('targetWidth');
        $targetHeight = $this->_request->getParameter('targetHeight');
        $newFileName = $this->_request->getParameter('newFileName');
        
        $newPath = './uploads/resized';
        $newRealPath = realpath($newPath);
        
        
        $newFilePath = $newPath.'/'.$newFileName;
        $newFileRealPath = $newRealPath.'/'.$newFileName;
        
        $file = new File();
        $file->unserialize($realPath);
        $image = new Image($file);
        $image->resize($newFileRealPath, $image->getImage(), 0, 0, $x1, $y1, $targetWidth, $targetHeight, $croppedWidth, $croppedHeight, 100);
        
        $this->_response->setAttribute('objects', $this->buildJsonArray(true, 'OK', $newFilePath, $newFileRealPath));
        
        $this->findForward("success");
    }
    
    /**
     * Returns the array for json encoding
     * 
     * @param bool   $status
     * @param string $str
     * @param string $httpPath
     * @param string $realPath
     * 
     * @return array
     */
    function buildJsonArray($status, $str, $httpPath, $realPath)
    {
         return array('status'=>$status, 'message'=>$str, 'path'=>$httpPath, 'realPath'=>$realPath);
    }
}
